package com.tuanzi.loan.business.validation.validator.family;

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.family.ProductMatchRule;
import com.tuanzi.loan.business.validation.annotation.family.ProductMatchRuleBusinessValidation;
import com.tuanzi.loan.core.exception.ValidateException;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.vo.view.family.ProductMatchRuleView;

public class ProductMatchRuleBusinessValidator implements ConstraintValidator<ProductMatchRuleBusinessValidation, ProductMatchRule> {

	@Override
	public void initialize(ProductMatchRuleBusinessValidation constraintAnnotation) {
	}

	@Override
	public boolean isValid(ProductMatchRule productMatchRule, ConstraintValidatorContext context) {
		ProductMatchRuleView.ProductMatchRulePriority priority = GsonUtils.toObject(productMatchRule.getPriorityJson(), ProductMatchRuleView.ProductMatchRulePriority.class);

		List<Integer> sorts = Lists.newArrayList(priority.getAmount(), priority.getApprovalRate(), priority.getNecessaryData(), priority.getOnlineTime()).parallelStream()
				.filter(x -> x != null).collect(Collectors.toList());

		if (sorts.parallelStream().filter(x -> x != null).distinct().count() != sorts.size()) {
			throw new ValidateException("存在重复的优先级,请输入正确的优先级");
		}

		return true;
	}

}
